﻿using System.Collections.Generic;
using System.Data.SQLite;
using System.Data.EntityClient;
using System.IO;
using System;

namespace DBContest
{
    public static class VendorsUtilities
    {
        public const string SQLITE_CONNECTION_STRING = "Data source = ../../VendorDatabase.db; Version = 3";
        private const string LOG_PATH = "../../VendorsLog.log";

        private static StreamWriter logWriter = new StreamWriter(LOG_PATH, true);

        public static void FirstInitialization()
        {
            InsertVendor("Morganbr", "08957767677/ 0985567654562", "bgconsumer@morganbr.bg");
            InsertVendor("Milka", "08345678384238", "consumer@milka.com");
            InsertVendor("PeshoFood", "02/5422238", "admin@pesho.bg");
            InsertVendor("Svoge", "0834123458", "HRcon@svoge.com");
            InsertVendor("uldram", "098897787788778", "baubau@avt.com");
        }

        public static void TestRead()
        {
            using (SQLiteConnection connection = new SQLiteConnection(SQLITE_CONNECTION_STRING))
            {
                string query = "Select * from vendors order by VendorName";
                using (SQLiteCommand comm = new SQLiteCommand(query, connection))
                {
                    connection.Open();
                    using (SQLiteDataReader reader = comm.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            System.Console.WriteLine("{0},{1},{2},{3}",
                                reader.GetValue(0), reader.GetValue(1), reader.GetValue(2), reader.GetValue(3));
                        }
                    }
                }
            }
        }

        public static void InsertVendor(string name, string phones, string email)
        {
            using (SQLiteConnection connection = new SQLiteConnection(SQLITE_CONNECTION_STRING))
            {
                string query =
                    string.Format(
                    "Insert into Vendors(VendorID, VendorName, Phones, Email)" +
                    "Values (NULL, '{0}', '{1}', '{2}')", name, phones, email);

                using (SQLiteCommand comm = new SQLiteCommand(query, connection))
                {
                    try
                    {
                        comm.ExecuteNonQuery();
                    }
                    catch (Exception e)
                    {
                        logWriter.WriteLine("{0} Insertion failed. Reason: {1}, {2} ",DateTime.Now , e.Message, e.InnerException);
                        logWriter.Flush();
                        
                    }
                }
            }
        }

    }
}
